import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import GestureLock from './GestureLock';
import { Result,NavBar } from 'antd-mobile'

import CryptoJS from 'crypto-js';

const LoginGesture = () => {
    const navigate = useNavigate();
    const [error, setError] = useState('');
    const [errorCount, setErrorCount] = useState(0);
    const [isLocked, setIsLocked] = useState(false);
    const [lockTimeLeft, setLockTimeLeft] = useState(0);
    const gesturePwd = localStorage.getItem('gesturePwd') || '';

    useEffect(() => {
        let timer;
        if (isLocked && lockTimeLeft > 0) {
            timer = setInterval(() => {
                setLockTimeLeft(prev => {
                    if (prev <= 1) {
                        clearInterval(timer);
                        setIsLocked(false);
                        return 0;
                    }
                    return prev - 1;
                });
            }, 1000);
        }
        return () => clearInterval(timer);
    }, [isLocked, lockTimeLeft]);

    const handleLogin = (inputPwd) => {
        if (isLocked) {
            setError(`账户已锁定，请等待${lockTimeLeft}秒后重试`);
            return false;
        }

        const hashedInputPwd = CryptoJS.SHA256(inputPwd).toString();
        if (hashedInputPwd === gesturePwd) {
            // 重置错误计数
            setErrorCount(0);
            // 生成假token
            const accessTokens = 'access_' + Math.random().toString(36).slice(2) + '_' + Date.now();
            const refreshTokens = 'refresh_' + Math.random().toString(36).slice(2) + '_' + Date.now();
            localStorage.setItem('accessTokens', accessTokens);
            localStorage.setItem('refreshTokens', refreshTokens);
            navigate('/layout/home');
            return true;
        } else {
            const newErrorCount = errorCount + 1;
            setErrorCount(newErrorCount);
            
            if (newErrorCount >= 5) {
                setIsLocked(true);
                setLockTimeLeft(30);
                setError(`密码错误5次，账户已锁定30秒`);
            } else {
                setError(`手势密码错误，已错误${newErrorCount}次，5次后将锁定账户`);
                setTimeout(()=>{
                    setError('');
                }, 3000);
            }
            return false;
        }
    };
    const back = () => {
        navigate('/login');
    }

    return (
        <div style={{
            height: '100%',
            background: 'linear-gradient(135deg, #e8f5e9 0%, #e3f2fd 100%)',
            display: 'flex',
            flexDirection: 'column',
            overflow:'hidden',
            width:'100%'
        }}>
            <NavBar onBack={back} style={{
                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                backdropFilter: 'blur(10px)',
                borderBottom: '2px solid var(--campus-primary, #4caf50)'
            }}>绘制图案</NavBar>

            <div style={{
                flex: 1,
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                padding: '20px',
                background: 'rgba(255, 255, 255, 0.1)',
                borderRadius: '20px',
                margin: '20px',
                backdropFilter: 'blur(10px)',
                border: '1px solid rgba(255, 255, 255, 0.2)',
                boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)'
            }}>
                <h2 style={{ 
                    textAlign: 'center', 
                    width: '100%',
                    color: 'var(--campus-text, #2e3d49)',
                    fontSize: '24px',
                    fontWeight: 'bold',
                    marginBottom: '30px',
                    textShadow: '0 2px 4px rgba(0, 0, 0, 0.1)'
                }}>手势登录</h2>

                {gesturePwd ? (
                    <GestureLock 
                        type={1} 
                        pwd={gesturePwd} 
                        onBack={handleLogin} 
                        disabled={isLocked} 
                        errorMessage={error} 
                        lockTimeMessage={isLocked ? `剩余锁定时间: ${lockTimeLeft}秒` : ''} 
                    />
                ) : (
                    <Result
                        status='warning'
                        title='警告提示'
                        description='您还没有设置手势密码呢，请您先登录进去再设置手势叭'
                        style={{
                            marginTop: '40%',
                            backgroundColor: 'rgba(255, 255, 255, 0.8)',
                            borderRadius: '15px',
                            padding: '20px',
                            backdropFilter: 'blur(10px)'
                        }}
                    />
                )}
            </div>
        </div>
    );
};

export default LoginGesture;